<?php
/*========================================= JooSam =========================================/
/																							/
/	Extention:		JooSam																	/
/	Created by:		ScriptPlanet.eu															/
/	Site:			http://www.scriptplanet.eu												/
/	Email:			support@scriptplanet.eu													/
/	Support:		http://www.scriptplanet.eu/support										/
/	Copyright:		2011 (c) ScriptPlanet.eu												/
/	License:		CC BY-NC-ND 3.0 ~ http://creativecommons.org/licenses/by-nc-nd/3.0/		/
/	File Version:	0001																	/
/																							/
/========================================== JooSam ========================================*/

// Joomla security
defined('_JEXEC') or die;

class SamdbHelper {

	public function samDBO($option,$query){

		## Turn off anoying errors.
		error_reporting(0);
		## Global var
		$result = '';
		
		## joosam conf
		$server		= SamdbHelper::checkSettings('sqlip');
		$port		= SamdbHelper::checkSettings('sqlport');
		$user		= SamdbHelper::checkSettings('sqluser');
		$prePass	= SamdbHelper::checkSettings('password');
		$password	= JoosamHelper::jscrypt('decode',$prePass);
		$database	= SamdbHelper::checkSettings('sqldb');
		
		
		## set/check port
		if ($port == '3306' OR $port == ''){
			$server = $server;
		}
		else{
			$server = $server.':'.$port;
		}

		## Mysqli Connect
		$sdb = new mysqli($server, $user, $password, $database);

		## Check and test mysqli connection
		if(mysqli_connect_error()){
			$result = array( 'error', 'Mysql Error: '.mysqli_connect_errno().' - '.mysqli_connect_error() );
		}
		
		## Mysql Work
		else{

			## Make sure only admin event ot admin request can call me
			if($option == 'event' OR $option == 'admreq'){
				$data = '';
				if($sql = $sdb->query($query)){
					while($row = $sql->fetch_assoc()){
						$data[] = $row;
					} $sql->free();
					$sdb->close();
					if($data != ''){
						$result = $data;
					}
					else{
						## COM_JOOSAM_MYSQL_NO_DATA
						$result = array( 'warning', 'Connection ok but no data found.');
					}
				}
				else{
					## COM_JOOSAM_MYSQL_BAD_QUERY
					$result = array( 'error', 'Error in the mysql query.');
				}
			}
			else{
				## COM_JOOSAM_MYSQL_NOT_JCALL
				$result = array( 'error', 'Wrong function is calling admin samdb.');
			}
		}

		## Data done. Return now
		return $result;
	}
	
	## Get settings
	protected function checkSettings($col){
		$setid = '1';
		$db =& JFactory::getDBO();
		$query = "
			SELECT ".$db->nameQuote($col)."
			FROM ".$db->nameQuote('#__joosam_settings')."
			WHERE ".$db->nameQuote('id')." = ".$setid."; ";
		$db->setQuery($query);
		$result = $db->loadResult();
		return $result;
	}
}